package com.mediacloud.app.newsmodule.fragment.recommend;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.eventTrack.TXReportManager;
import com.google.gson.Gson;
import com.mediacloud.app.assembly.util.FunKt;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.ArticleListData;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.component.CSubscribeStyleAdapter;
import com.mediacloud.app.newsmodule.adaptor.component.IEvent;
import com.mediacloud.app.newsmodule.adaptor.component.XAbsComponentHolder;
import com.mediacloud.app.newsmodule.guanzhu.GuanZhuModel;
import com.mediacloud.app.newsmodule.guanzhu.PageRecords;
import com.mediacloud.app.newsmodule.utils.spider.SpiderKit;
import com.mediacloud.app.reslib.enums.AppFactoryGlobalConfig;
import com.zimeiti.activity.XSubscribeMoreActivity;
import com.zimeiti.controler.AttentionEvent;
import com.zimeiti.details.MediaAuthorDetailActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 号推荐组件
 */
public class HaoRecommentComponent extends BaseComponentRelatedView implements View.OnClickListener, Callback, IEvent {
    public RecyclerView attentionList;
    public CSubscribeStyleAdapter subscribeStyleAdapter;
    Call cancelable;
    View progressBar;

    public CatalogItem catalogItem;
    private boolean isAdded = false;

    private Context mContext;
    public HaoRecommentComponent(Context context) {
        super(context);
        mContext = context;
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        header = new XAbsComponentHolder(mRootView) {
            @Override
            public boolean isDetail() {
                return false;
            }

            @Override
            public void onClick(View v) {
                onMoreClick(v);
            }
        };
    }

    @Override
    public void setData(ArticleItem articleItem,String article_id, ComponentItem component, int type) {
        super.setData(articleItem,article_id, component, type);
        setVisibility(VISIBLE);
        mRootView.setVisibility(VISIBLE);
        this.componentItem = component;
        header.setComponent(componentItem);

        attentionList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        subscribeStyleAdapter = new CSubscribeStyleAdapter(mContext);
        subscribeStyleAdapter.onItemClickListener = this;
        attentionList.setAdapter(subscribeStyleAdapter);
        attentionList.setItemAnimator(null);

        String orderField = "";
        String author_tag_id_2 = "";
        try {

            JSONObject other_field = componentItem.orginDataObject.optJSONObject("other_field");
            author_tag_id_2 = other_field.optString("author_tag_id_2");
            int trigger=1;
            if(other_field!=null){
                String recommend_strategy = other_field.optString("recommend_strategy","0");
                if(recommend_strategy.equals("1")){
                    orderField ="read_number";
                }else if(recommend_strategy.equals("2")){
                    orderField ="read_number";
                }else {
                    orderField = null;
                }
                trigger = other_field.optInt("trigger", 1);
            }
            if (trigger == 2) {
                if (!AppFactoryGlobalConfig.ServerAppConfigInfo.OtherConfig.isTodayFirst) {
                    if (mRootView.getLayoutParams() != null) {
                        mRootView.getLayoutParams().height = 1;
                        mRootView.requestLayout();
                    }
                    return;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mRootView.getLayoutParams() != null) {
            mRootView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
            mRootView.requestLayout();
        }
        subscribeStyleAdapter.component = componentItem;
        header.setComponent(componentItem);
        SpiderKit.INSTANCE.getGuessYouLikeList(mContext, component.getPage(), orderField,author_tag_id_2,this);

        header.setMoreListener(this);
    }



    @Override
    public int setLayoutRes() {
        return R.layout.component_type16;
    }

    @Override
    public void initOtherViews() {
        progressBar = mRootView.findViewById(R.id.progressBar);
        attentionList = mRootView.findViewById(R.id.attentionList);
    }

    @Override
    public void onDataSuccess(ArticleListData data) {

    }

    @Override
    public void onDataFault(Object data) {

    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Override
    public void onClick(View v) {
        if (FunKt.isFastClick()){
            if (v.getId() == R.id.moreText) {
                if (componentItem != null) {
                    //集中处理更多点击事件
                    TXReportManager.getInstance().subtab_more_clk(componentItem.title);
                }
            }
            if (v.getParent() instanceof RecyclerView) {//点击事件必须是item布局最外层
                if (subscribeStyleAdapter.getData() == null || subscribeStyleAdapter.getData().size() == 0)
                    return;
                int position = attentionList.getChildAdapterPosition(v);
                position = position % subscribeStyleAdapter.getData().size();
                if (position == -1) {
                    return;
                }
                PageRecords pageRecords = subscribeStyleAdapter.getItem(position);
                if (pageRecords != null) {
                    Intent intent = new Intent(attentionList.getContext(), MediaAuthorDetailActivity.class);
                    intent.putExtra("author_id", pageRecords.getUserId());
                    attentionList.getContext().startActivity(intent);

                }
            } else {
                Intent intent = new Intent();
                intent.putExtra("title", componentItem.getTitle());
                intent.putExtra("entrance_name", TXReportManager.getInstance().getFirstTabInfo().getTabName()+"-"+TXReportManager.getInstance().getCurrentChannelInfo().getTabName()+"-"+componentItem.getTitle());
                intent.setClass(attentionList.getContext(), XSubscribeMoreActivity.class);
                attentionList.getContext().startActivity(intent);

            }
        }

    }

    @Override
    public void onFailure(Call call, IOException e) {
        progressBar.post(() -> {
            progressBar.setVisibility(View.GONE);
        });
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        try {
            GuanZhuModel result = new Gson().fromJson(response.body().string(), GuanZhuModel.class);
            if (result != null) {
                subscribeStyleAdapter.getData().clear();
                subscribeStyleAdapter.setData(result.getData().getPageRecords());
                progressBar.post(() -> {
                    subscribeStyleAdapter.notifyDataSetChanged();
                    progressBar.setVisibility(View.GONE);
                });

            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void destroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (cancelable != null) {
            if (!cancelable.isCanceled()) {
                cancelable.cancel();
            }
            cancelable=null;
        }
        if (subscribeStyleAdapter != null) {
            subscribeStyleAdapter.destroy();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAttentionEvent(AttentionEvent attentionEvent) {
        subscribeStyleAdapter.notifyDataSetChanged();
    }
}